package fire.and.near.challenger;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.Response;

import fire.and.near.challenger.camera.CameraHelper;
import fire.and.near.challenger.database.ChallengeModel;
import fire.and.near.challenger.database.ChallengeModel.ChallengeType;
import fire.and.near.challenger.database.DatabaseActivity;
import fire.and.near.challenger.database.DatabaseAsyncTask;
import fire.and.near.challenger.database.DatabaseAsyncTask.DatabaseQueryOptions;
import fire.and.near.challenger.database.DatabaseResponse;
import fire.and.near.challenger.database.TableConstants.ChallengesTable;
import fire.and.near.challenger.database.TableConstants.FriendsTable;
import fire.and.near.challenger.facebook.FacebookActionAdapter;
import fire.and.near.challenger.facebook.FacebookHelper;
import fire.and.near.challenger.facebook.MessageBuilder;
import fire.and.near.challenger.facebook.MessageType;
import fire.and.near.challenger.util.Consts;

// TODO: WTF are the modes for?
public class PendingChallengeDetailsActivity extends ActionBarActivity
		implements DatabaseActivity {

	private ChallengeModel mChallenge = null;
	private boolean databaseWorking = false;
	private boolean facebookPosting = false;

	private TextView textViewDescription = null;
	private TextView textViewAnswer = null;
	private TextView textViewFriendName = null;
	private ImageView imageViewPhoto = null;

	private final ActionBarActivity self = this;
	private final FacebookHelper mFbHelper = LoginActivity.mFbHelper;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pending_challenge_details);

		if (savedInstanceState == null) {
			initChallenge(getIntent().getExtras());
		}

		this.textViewDescription = (TextView) findViewById(R.id.textView_description);
		this.textViewAnswer = (TextView) findViewById(R.id.textView_answer);
		this.textViewFriendName = (TextView) findViewById(R.id.textView_friend_name);
		this.imageViewPhoto = (ImageView) findViewById(R.id.imageView_photo);

		if (mChallenge.getDescription() != null) {
			textViewDescription.setText(mChallenge.getDescription());
		} else {
			textViewDescription.setText("---");
		}
		
		if (mChallenge.getAnswer() != null) {
			textViewAnswer.setText(mChallenge.getAnswer());
		} else {
			textViewAnswer.setText("---");
		}

		if (mChallenge.getChallenger().getName() != null) {
			textViewFriendName.setText(mChallenge.getChallenger().getName());
		} else if(mChallenge.getChallengedID() == mChallenge.getChallenger().getFbID()){
			textViewFriendName.setText(Consts.ME);
		} else {
			textViewFriendName.setText(Consts.COMPANY_NAME);
		}
		
		if (mChallenge.getPhotoPath() != null) {
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			
			BitmapFactory.decodeFile(mChallenge.getPhotoPath(),
					options);
			
			int width = imageViewPhoto.getWidth();
			int height = imageViewPhoto.getHeight();
			
			options = CameraHelper
					.makeSampleOptions(this, options, width, height);
			
			options.inJustDecodeBounds = false;

			Bitmap bitmap = BitmapFactory.decodeFile(mChallenge.getPhotoPath(),
					options);
			
			imageViewPhoto.setImageBitmap(bitmap);
		} else {
			imageViewPhoto.setVisibility(View.GONE);
		}

		((Button) findViewById(R.id.button_accept)).setText("Publish");
		((Button) findViewById(R.id.button_decline)).setText("Delete");

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putInt(ChallengesTable.ID, this.mChallenge.getID());
		outState.putString(ChallengesTable.DESCRIPTION,
				this.mChallenge.getDescription());
		outState.putString(ChallengesTable.HASHTAG,
				this.mChallenge.getHashtag());
		outState.putInt(ChallengesTable.CHALLENGE_TYPE,
				this.mChallenge.getChallengeTypeForDatabase());
		outState.putLong(ChallengesTable.CHALLENGED_ID, this.mChallenge
				.getChallengedID());
		outState.putLong(ChallengesTable.CHALLENGER_ID, this.mChallenge
				.getChallenger().getFbID());
		outState.putString(FriendsTable.NAME, this.mChallenge.getChallenger()
				.getName());
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		initChallenge(savedInstanceState);
		super.onRestoreInstanceState(savedInstanceState);
	}

	private void initChallenge(Bundle extras) {
		this.mChallenge = new ChallengeModel();
		this.mChallenge.setID(extras.getInt(ChallengesTable.ID));
		this.mChallenge.setDescription(extras
				.getString(ChallengesTable.DESCRIPTION));
		this.mChallenge.setAnswer(extras.getString(ChallengesTable.ANSWER));
		this.mChallenge.setHashtag(extras.getString(ChallengesTable.HASHTAG));
		this.mChallenge.setPhotoPath(extras
				.getString(ChallengesTable.PHOTO_PATH));
		this.mChallenge.setChallengeType(extras
				.getInt(ChallengesTable.CHALLENGE_TYPE));
		this.mChallenge.setChallengedID(extras
				.getLong(ChallengesTable.CHALLENGED_ID));
		this.mChallenge.getChallenger().setFbID(
				extras.getLong(ChallengesTable.CHALLENGER_ID));
		this.mChallenge.getChallenger().setName(
				extras.getString(FriendsTable.NAME));
		this.mChallenge
				.setAccepted(extras.getBoolean(ChallengesTable.ACCEPTED));
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_logout) {
			LoginActivity.mFbHelper.logout();
			finish();
			return true;
		}

		if (id == R.id.action_details) {
			Intent i = new Intent(this, UserDetailsActivity.class);
			startActivity(i);
			
			return true;
		}
		
		return super.onOptionsItemSelected(item);
	}

	// UPLOAD CHALLENGE
	public void acceptChallenge(View view) {
		
		if (!facebookPosting) {
			facebookPosting = true;
			
			Bitmap bitmap = null;
			String photoPath = this.mChallenge.getPhotoPath();
	
			if (mChallenge.getChallengeType() == ChallengeType.PHOTO
					&& photoPath == null) {
				Toast.makeText(self, "No photo", Toast.LENGTH_LONG).show();
				return;
			}
			
			findViewById(R.id.progressBarPendingDetails)
				.setVisibility(View.VISIBLE);
	
			if (photoPath != null) {
				bitmap = BitmapFactory.decodeFile(photoPath);
			}
	
			MessageBuilder msgBuilder = null;
	
			MessageType type = mChallenge.getChallenger().getName() != null ? 
									MessageType.CompleteChallenge : 
									MessageType.SelfChallenge;
			
			msgBuilder = new MessageBuilder(mChallenge.getDescription(),
											mChallenge.getAnswer(), 
											mChallenge.getHashtag(),
											type);
	
			mFbHelper.postStatusUpdate(self, msgBuilder.build(), ""
					+ mChallenge.getChallenger().getFbID(), bitmap,
					new FacebookActionAdapter() {
						@Override
						public void onActionCompleted(Response response) {
	
							if (response.getError() == null) {
								Toast.makeText(self,
										"Posted on facebook",
										Toast.LENGTH_LONG).show();
								new DatabaseAsyncTask(self,
										DatabaseQueryOptions.COMPLETE)
										.execute(mChallenge.getID());
							} else {
								Toast.makeText(self,
										"Error ocurred while posting on facebook.",
										Toast.LENGTH_LONG).show();
								Log.i("UploadStatusWithPic", response.toString());
							}
							
							findViewById(R.id.progressBarPendingDetails)
								.setVisibility(View.GONE);
						}
					});
		}
	}

	// DELETE CHALLENGE
	public void declineChallenge(View view) {
		if (databaseWorking) {
			return;
		}
		databaseWorking = true;
		
		new DatabaseAsyncTask(this, DatabaseQueryOptions.COMPLETE)
				.execute(this.mChallenge.getID());
	}

	@Override
	public void processDatabaseResponse(DatabaseResponse result) {
		if (result.isSuccessful()) {
			Toast.makeText(this, "Challenge deleted.", Toast.LENGTH_LONG)
					.show();
		}
		
		Intent data = new Intent();
		data.putExtra(Consts.SUCCESS, result.isSuccessful());

		if (getParent() == null) {
		    setResult(Activity.RESULT_OK, data);
		} else {
		    getParent().setResult(Activity.RESULT_OK, data);
		}
		
		finish(); // go back to pending challenges activity
	}

	@Override
	public void setDatabaseWorking(boolean working) {
		this.databaseWorking = working;
	}
}
